package com.tdd.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * @author tudedong
 * @description
 * @date 2020-06-13 15:05:58
 */
public class ServiceRegistry {

    private static final String BASE_SERVICE = "/zookeeper";
    private static final String SERVICE_NAME = "/server";

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private static String registryAddress = "47.101.41.95:2181";

    public ServiceRegistry() {
    }



    public void register(String data){
        if(data != null){
            //连接zk服务器
            ZooKeeper zooKeeper = connectServer();
            if(zooKeeper != null){
                //创建znode节点
                createNode(zooKeeper,data);
            }
        }

    }

    /**
     * 创建znode节点
     * @param zooKeeper
     * @param data
     */
    private void createNode(ZooKeeper zooKeeper, String data) {
        String path = BASE_SERVICE+SERVICE_NAME;
        try {
            Stat exists = zooKeeper.exists(BASE_SERVICE+SERVICE_NAME,false);
            if(exists == null){
                zooKeeper.create(path,"".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            zooKeeper.create(path+"/child",data.getBytes("utf-8"),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);

            System.out.println("服务器注册成功,路径为:["+path+"/child],数据为:["+data+"]");
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接zk服务器
     * @return
     */
    private ZooKeeper connectServer() {
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(registryAddress, 50000, new Watcher() {
                public void process(WatchedEvent watchedEvent) {

                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
        }catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
